/**
 *
 */
package com.beamfield.controller.api.mb;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.beamfield.common.ApiResult;
import com.beamfield.common.CommonUtils;
import com.beamfield.common.DateSwitcher;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.MbBaseController;
import com.beamfield.dictionary.code;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.model.DeviceMaintain;
import com.beamfield.model.DeviceWork;
import com.beamfield.model.Inbound;
import com.beamfield.model.InboundCheckWithBLOBs;
import com.beamfield.modelVo.RebarInboundVo;
import com.beamfield.modelVo.SystemDictionaryDataVo;
import com.beamfield.service.manage.device.DeviceService;
import com.beamfield.service.manage.material.InboundService;
import com.beamfield.service.manage.material.PurchaseService;
import com.beamfield.service.manage.sys.DictonaryService;
import com.beamfield.service.manage.sys.SuppliesService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 进场管理
 *
 * @author mintonzhang@163.com
 * @date 2018年6月13日
 */
@RestController
@RequestMapping("/mb_api/inbound")
public class MbInboundController extends MbBaseController {

    @Autowired
    private SuppliesService suppliesService;
    @Autowired
    private PurchaseService purchaseService;
    @Autowired
    private InboundService inboundService;
    @Resource
    private DictonaryService dictonaryService;
    @Resource
    private DeviceService deviceService;

    @Value("${session.beam}")
    private String beam;

    @RequestMapping(value = "/material/material")
    public ModelAndView material(){
        return new ModelAndView();
    }

    /**
     * 获取初始化处理进度
     * @param request
     * @return
     */
    @RequestMapping(value = "/material/inbound/getProgressData",method = RequestMethod.GET)
    @ResponseBody
    public ApiResult getProgressData(HttpServletRequest request){
        Map<String,Double> resMap = new HashMap<>();
        Object progress = request.getSession().getAttribute("save_embed_progress");
        resMap.put("progressValue", progress == null ? 0L : (Double) progress);
        return new ApiResult(resMap);
    }

    /**
     * 查询材料库存
     *
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     * @param req
     * @return
     */
    @RequestMapping("/getSuppliesByType")
    public ApiResult getSuppliesByType(HttpServletRequest req) {
        JSONObject body = super.getBody(req);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
        String type = body.getString("type");
        try {
            Long beamId = super.getLogInfo(req).getBeamId();

            return suppliesService.getSuppliesByType(type, beamId);
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    /**
     * 根据材料id查询所有的计划及入库详细
     *
     * @date 2018年6月13日
     * @author mintonzhang@163.com
     * @return
     */
    @RequestMapping("/getPurchaseBySuppliesId")
    public ApiResult getPurchaseBySuppliesId(HttpServletRequest req) {
        JSONObject body = super.getBody(req);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }


        Long beamId = super.getLogInfo(req).getBeamId();
        String supplies_id = body.getString("supplies_id");
        String status = body.getString("status");

        if(supplies_id == null){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "supplies_id不能为空");
        }
        PageResult pageResult = purchaseService.getPurchaseBySuppliesId(supplies_id, beamId, null, status, null, 0, null);
        return  new ApiResult(pageResult);
    }

    /**
     * 查询计划详细
     *
     * @date 2018年6月14日
     * @author mintonzhang@163.com
     * @param req
     * @param keywords
     * @param date
     * @param supplies_id
     * @param plan_id
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping("/getPurchaseInboundDetail")
    public PageResult getPurchaseInboundDetail(HttpServletRequest req, String keywords, String date, String supplies_id,
                                               Long plan_id, Integer offset, Integer limit) {
        if (CommonUtils.checkMissParam(supplies_id, plan_id)) {
            return new PageResult(0, 0, null);
        }
        return inboundService.getPurchaseInboundDetail(supplies_id, getBeamId(req), keywords, date, plan_id, offset,
                limit);
    }


    /**
     *
     * @param req
     * @return
     */
    @RequestMapping("/upload")
    public ApiResult upload(HttpServletRequest req) {
        MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
        CommonsMultipartFile file = (CommonsMultipartFile) mRequest.getFile("file");
        Long id = saveFile(file);
        return new ApiResult(id);
    }


    /**
     * 入库申请（钢筋）
     * @date 2018年6月14日
     * @author mintonzhang@163.com
     * @param req
     * @return
     */
    @RequestMapping("/saveInboundRebar")
    public ApiResult saveInboundRebar(HttpServletRequest req) {
        JSONObject body = super.getBody(req);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }


        Long beamId = super.getLogInfo(req).getBeamId();
        Long userId = super.getUserId(req);

        //运货单号
        String logisitcs_number = body.getString("logisitcs_number");
        //进场日期
        String itime_str = body.getString("itime_str");
        //材料
        String supplies_id = body.getString("supplies_id");
        //生产厂家
        String manufacturer = body.getString("manufacturer");
        //仓库id
        String storage_place = body.getString("storage_place");
        //计划单号
        String purchase_plan_id = body.getString("purchase_plan_id");
        //project_id
        String project_id = body.getString("project_id");
        //二维码内容
        String rebarInbound = body.getString("rebarInbound");

        String file_id = body.getString("file_id");

        if(rebarInbound == null){
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "rebarInbound不能为空");
        }
        Inbound inbound = new Inbound();
        try {

            inbound.setQuality_file(Long.parseLong(file_id));

            inbound.setLogisitcs_number(logisitcs_number);
            inbound.setSupplies_id(supplies_id);
            inbound.setManufacturer(manufacturer);
            inbound.setStorage_place(storage_place);
            inbound.setPurchase_plan_id(Long.parseLong(purchase_plan_id));
            inbound.setProject_id(Long.parseLong(project_id));
            inbound.setAddtime(new Date());
            inbound.setBeam_id(beamId);
            inbound.setOperator(userId);
            inbound.setUpdater(userId);
            inbound.setUpdatetime(new Date());
            inbound.setQuality_file(0L);
            inbound.setType(2);
            inbound.setItime(new Date());

            //2018-05-31|11:54:57|JB|2002 kg|07-094|C1-3051075|HRB400|22X12|200
            //拆解条码内容
            String[] split = rebarInbound.split("\\|");
            RebarInboundVo  rebarInboundVo = new RebarInboundVo();
            rebarInboundVo.setNumber(Double.parseDouble(split[3].split(" ")[0]));
            rebarInboundVo.setBatch_num(split[5]);
            rebarInboundVo.setCheck_date_str(split[0]);
            rebarInboundVo.setCount(Integer.parseInt(split[8]));
            rebarInboundVo.setCheck_num(split[4]);
            List<RebarInboundVo> rebarInboundVoList = new ArrayList<>();
            rebarInboundVoList.add(rebarInboundVo);
            if(!inboundService.checkRebarInbound(inbound,rebarInboundVoList,beamId,userId)) {
                return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"入库数量超标");
            }
            Long aLong = inboundService.saveInboundRebar(inbound, rebarInboundVoList);
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),aLong+"");
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }
    /**
     * 入库申请(预埋件)
     * @date 2018年6月14日
     * @author mintonzhang@163.com
     * @param req
     * @param itime_str
     * @param inbound
     * @return
     */
    @RequestMapping("/material/inbound/saveInboundEmbed")
    public ApiResult saveInboundEmbed(HttpServletRequest req, String itime_str,Integer count, Inbound inbound) {
        try {
            if (CommonUtils.checkMissParam(inbound,
                    inbound.getProject_id(),
                    inbound.getPurchase_plan_id(),
                    inbound.getSupplies_id(),
                    inbound.getManufacturer(),
                    inbound.getLogisitcs_number(),
                    inbound.getBatch_number(),
                    inbound.getStorage_place(),
                    itime_str,
                    count)) {
                return new ApiResult(HttpResultEnum.MIS_PARAM.getCode());
            }
            //处理接收的文件
            MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
            CommonsMultipartFile file = (CommonsMultipartFile) mRequest.getFile("file");
            Long id = saveFile(file);
            inbound.setQuality_file(id);

            inbound.setNumber(count.doubleValue());
            inbound.setAddtime(new Date());
            inbound.setBeam_id(getBeamId(req));
            inbound.setOperator(getUserId(req));
            inbound.setUpdater(getUserId(req));
            inbound.setUpdatetime(new Date());
            inbound.setQuality_file(0L);
            inbound.setType(3);
            inbound.setItime(DateSwitcher.string2Date(itime_str,"yyyy-MM-dd"));

            if(!inboundService.checkInbound(inbound)) {
                return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),"入库数量超标");
            }
            //保存
            inboundService.saveEmbarInbound(inbound, count, req);
            req.getSession().setAttribute("inbound_session" + getUserId(req), inbound);
            req.getSession().setAttribute("inbound_session_int_data" + getUserId(req),count);
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"操作成功");

        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    @RequestMapping("/material/inbound/getCheckNum")
    public ApiResult getCheckNum(HttpServletRequest request){
        String checkDep = request.getParameter("checkDep");
        Long beamId = super.getBeamId(request);
        if(StringUtils.isEmpty(checkDep)){
            return new ApiResult();
        }
        String checkNum = inboundService.getCheckNum(checkDep, beamId);
        return new ApiResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(), checkNum);
    }

    /**
     * 入库申请检查单
     * @date 2018年6月14日
     * @author mintonzhang@163.com
     * @param req
     * @param wdate_str
     * @param inboundCheck
     * @return
     */
    @RequestMapping("/material/inbound/saveInboundCheck")
    public ApiResult saveInboundCheck(HttpServletRequest req,String wdate_str,InboundCheckWithBLOBs inboundCheck,String inboundid) {
        try {
            if (CommonUtils.checkMissParam(inboundCheck,
                    inboundid,
                    inboundCheck.getCheck_dep(),
                    inboundCheck.getSample_num(),
                    inboundCheck.getTest_num(),
                    inboundCheck.getLevel(),
                    inboundCheck.getNominal_diameter(),
                    inboundCheck.getRepresent_num(),
                    inboundCheck.getStorage_place(),
                    inboundCheck.getSite(),
                    inboundCheck.getSample_describe(),
                    inboundCheck.getTest_standard(),
//                    inboundCheck.getTest_project(),
                    inboundCheck.getConsigner(),
                    inboundCheck.getAddress(),
                    inboundCheck.getAuthorize_agency(),
                    inboundCheck.getWitness(),
                    wdate_str)) {
                return new ApiResult(HttpResultEnum.MIS_PARAM);
            }
            inboundCheck.setAddtime(new Date());
            inboundCheck.setBeam_id(getBeamId(req));
            inboundCheck.setOperator(getUserId(req));
            inboundCheck.setUpdater(getUserId(req));
            inboundCheck.setUpdatetime(new Date());
            inboundCheck.setWdate(DateSwitcher.string2Date(wdate_str, "yyyy-MM-dd"));
            inboundService.saveInboundAndCheck(inboundCheck, getUserId(req), getBeamId(req),req,inboundid);
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"操作成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    @RequestMapping("/material/inbound/getDetailByInboundId")
    public PageResult getInboundDataById(Integer offset, Integer limit, Long inbound_id,Integer type) {
        if(CommonUtils.checkMissParam(inbound_id,type)) {
            return new PageResult(0, 0, null);
        }
        return inboundService.getInboundDataById(offset, limit, inbound_id, type);
    }

    /**
     * 下载预埋件或者钢筋的入库二维码
     * @param response
     * @param inboundId
     * @param inboundType
     * @return
     */
    @RequestMapping("/material/inbound/downloadInboundDetail")
    public String downloadInboundDetail(HttpServletResponse response, Long inboundId, Integer inboundType) {
        if(CommonUtils.checkMissParam(inboundId, inboundType)) {
            return "系统错误";
        }
        try {
            return inboundService.downloadInboundDetail(response, inboundId, inboundType);
        }catch (Exception e){
            e.printStackTrace();
            return "系统错误";
        }
    }
    /**普通材料入库
     * @return
     */
    @RequestMapping("/supplies/materialApproach/materialStorage")
    public ModelAndView materialStorage(){
        return new  ModelAndView();
    }
    @RequestMapping("/supplies/materialApproach/jieguotongzhiDetail")
    public ModelAndView jieguotongzhiDetail(){
        return new  ModelAndView();
    }


    /**
     * 普通材料入库申请
     * @return
     */
    @RequestMapping("/supplies/materialApproach/materialStorageCheck")
    public ModelAndView materialStorageCheck(){
        return new  ModelAndView();
    }

    /**
     * 预埋件
     * @return
     */
    @RequestMapping("/supplies/materialApproach/embed/embedStrage")
    public ModelAndView embedStrage(){
        return new  ModelAndView();
    }

    /**
     * 预埋件
     * @return
     */
    @RequestMapping("/supplies/materialApproach/embed/embedStrageCheck")
    public ModelAndView embedStrageCheck(){
        return new  ModelAndView();
    }



    /**
     * 主材料钢筋
     * @return
     */
    @RequestMapping("/supplies/materialApproach/rebar/rebarStrage")
    public ModelAndView rebarStrage(){
        return new  ModelAndView();
    }

    @RequestMapping("/material/inbound/getTestList")
    public List<SystemDictionaryDataVo> getTestList(HttpSession session){
        long beam_id = (long) session.getAttribute(beam);
        List<SystemDictionaryDataVo> list = dictonaryService.getDicByCode(code.test_project,beam_id);
        return list;
    }

    /**保存运转记录
     * @param session
     * @param workJson
     * @return
     */
    @RequestMapping("/saveWork")
    @ResponseBody
    public ApiResult saveWork(HttpServletRequest req,HttpSession session){
    	JSONObject body = super.getBody(req);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
    	Long beamId = super.getBeamId(req);
    	Long userId = super.getLogInfo(req).getUserId();
        ApiResult apiResult;
        try {
        	String start_date = body.getString("start_date");
        	String end_date = body.getString("end_date");
        	String device_id = body.getString("device_id");
        	String inbound_id = body.getString("inbound_id");
        	String work_content = body.getString("work_content");
        	String work_sum = body.getString("work_sum");
        	String sg_no = body.getString("sg_no");
        	String fule = body.getString("fule");
            DeviceWork deviceWork = new DeviceWork();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            deviceWork.setEnd_date(sdf.parse(end_date));
            deviceWork.setStart_date(sdf.parse(start_date));
            deviceWork.setDevice_id(CommonUtils.parseLong(device_id, 0));
            deviceWork.setInbound_id(CommonUtils.parseLong(inbound_id, 0));
            deviceWork.setWork_content(work_content);
            deviceWork.setWork_sum(work_sum);
            deviceWork.setSg_no(sg_no);
            deviceWork.setFule(CommonUtils.parseInt(fule, 0));
            apiResult = deviceService.saveWork(deviceWork, beamId, userId);
            return apiResult;
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

    /**保存运转记录
     * @param session
     * @param workJson
     * @return
     */
    @RequestMapping("/saveMaintain")
    @ResponseBody
    public ApiResult saveMaintain(HttpServletRequest req,HttpSession session){
    	JSONObject body = super.getBody(req);
        if(body == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(), HttpResultEnum.MIS_PARAM.getMessage());
        }
    	Long beamId = super.getBeamId(req);
    	Long userId = super.getLogInfo(req).getUserId();
        ApiResult apiResult;
        try {
        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        	String start_date = body.getString("start_date");
        	String end_date = body.getString("end_date");
        	String device_id = body.getString("device_id");
        	String inbound_id = body.getString("inbound_id");
        	String maintain_content = body.getString("maintain_content");
        	String maintain_operator = body.getString("maintain_operator");
        	String appr_operator = body.getString("appr_operator");
        	String maintain_type = body.getString("maintain_type");
        	DeviceMaintain deviceMaintain = new DeviceMaintain();
        	deviceMaintain.setMaintain_type(maintain_type);
        	deviceMaintain.setAppr_operator(appr_operator);
        	deviceMaintain.setMaintain_operator(maintain_operator);
        	deviceMaintain.setMaintain_content(maintain_content);
        	deviceMaintain.setInbound_id(CommonUtils.parseLong(inbound_id, 0));
        	deviceMaintain.setDevice_id(CommonUtils.parseLong(device_id, 0));
        	deviceMaintain.setStart_date(sdf.parse(start_date));
        	deviceMaintain.setEnd_date(sdf.parse(end_date));
            apiResult = deviceService.saveMaintain(deviceMaintain, beamId, userId);
            return apiResult;
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResult(HttpResultEnum.EXCEPTION.getCode());
        }
    }

}
